/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mapfinal.server.auth.service.impl;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import com.jfinal.kit.Ret;
import com.lambkit.common.service.LambkitModelServiceImpl;
import com.lambkit.core.aop.AopKit;
import com.mapfinal.server.MapfinalServer;
import com.mapfinal.server.auth.RoleService;
import com.mapfinal.server.auth.model.AuthAccess;
import com.mapfinal.server.auth.model.AuthRule;
import com.mapfinal.server.auth.model.Role;

/**
 * @author yangyong 
 * @website: www.lambkit.com
 * @email: gismail@foxmail.com
 * @date 2020-09-23
 * @version 1.0
 * @since 1.0
 */
public class RoleServiceImpl extends LambkitModelServiceImpl<Role> implements RoleService {
	
	private Role DAO = null;
	
	public Role dao() {
		if(DAO==null) {
			DAO = AopKit.singleton(Role.class);
		}
		return DAO;
	}
	
	public Role getRole(Long userid) {
		Role model = dao().findFirst("select * from mf_role as r, mf_role_user as u where r.id=u.role_id and u.user_id=?", userid);
		return model;
	}
	
	/**
	 * shiro
	 * @param userid
	 * @return
	 */
	public List<Role> getRoles(Long userid) {
		return dao().find("select * from mf_role as r, mf_role_user as u where r.id=u.role_id and u.user_id=?", userid);
	}
	
	public List<Role> getAllRoles() {
		return dao().find("select * from mf_role");
	} 

	
	/**
	 * 添加权限
	 */
	public Ret addPermission(int roleId, int permissionId) {
		if (roleId == 1) {
			return Ret.fail("msg", "超级管理员天然拥有所有权限，无需分配");
		}

		AuthAccess rolePermission = new AuthAccess().set("role_id", roleId).set("rule_id", permissionId);
		boolean flag = rolePermission.save();
		return flag ? Ret.ok("msg", "添加权限成功") : Ret.fail("msg", "添加权限失败");
	}

	/**
	 * 删除权限
	 */
	public Ret deletePermission(int roleId, int permissionId) {
		if (roleId == 1) {
			return Ret.fail("msg", "超级管理员天然拥有所有权限，不能删除权限");
		}

		int r = MapfinalServer.db().delete("delete from mf_auth_access where role_id=? and rule_id=?", roleId, permissionId);
		return r > 0 ? Ret.ok("msg", "删除权限成功") : Ret.fail("msg", "删除权限失败");
	}
	
	/**
	 * 标记出 role 拥有的权限，用于在界面输出 checkbox 的 checked 属性
	 * 未来用 permission left join role_permission 来优化
	 */
	public void markAssignedPermissions(Role role, List<AuthRule> permissionList) {
		// id 为 1 的超级管理员默认拥有所有权限
		if (role.getId() == 1) {
			for (AuthRule permission : permissionList) {
				permission.put("assigned", true);
			}
			return ;
		}
		String sql = "select role_id from mf_auth_access where role_id=? and rule_id=? limit 1";
		for (AuthRule permission : permissionList) {
			Integer roleId = MapfinalServer.db().queryInt(sql, role.getId(), permission.getId());
			if (roleId != null) {
				// 设置 assigned 用于界面输出 checked
				permission.put("assigned", true);
			}
		}
	}
	
	/**
	 * 根据 controller 将 permission 进行分组
	 */
	public LinkedHashMap<String, List<AuthRule>> groupByController(List<AuthRule> permissionList) {
		LinkedHashMap<String, List<AuthRule>> ret = new LinkedHashMap<String, List<AuthRule>>();
		for (AuthRule permission : permissionList) {
			String controller = permission.getType();
			List<AuthRule> list = ret.get(controller);
			if (list == null) {
				list = new ArrayList<AuthRule>();
				ret.put(controller, list);
			}

			list.add(permission);
		}

		return ret;
	}
}
